//
//  AFNwebManager.m
//  AFNwebservice
//
//  Created by 泽华伟业 on 16/5/7.
//  Copyright © 2016年 泽华伟业. All rights reserved.
//

#import "AFNwebManager.h"
#import <AFNetworking.h>
#import <MBProgressHUD.h>
#import "AppDelegate.h"

@interface AFNwebManager ()

@property (nonatomic,strong) AFHTTPSessionManager *manager;
@end
@implementation AFNwebManager

+ (AFNwebManager *)shareAFNWebManager
{
    static AFNwebManager *afnManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        afnManager = [[self alloc] init];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        afnManager.manager = manager;
    });
    return afnManager;
}

- (void)SOAPData:(NSDictionary *)pratams soapMethod:(NSString *)soapMethod success:(void (^)(id))success failure:(void (^)(void))failure
{
    NSString *soapbody = [[NSString alloc] init];
    for(NSString *str in pratams.allKeys)
    {
        soapbody = [soapbody stringByAppendingString:[NSString stringWithFormat:@"<%@>%@</%@>\\",str,[pratams objectForKey:str],str]];
    }
    
    NSString *soapStr = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\
                         <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\
                         xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
                         <soap:Header>\
                         </soap:Header>\
                         <soap:Body>\
                         <%@ xmlns=\"http://tempuri.org/\">\
                         %@\
                         </%@>\
                         </soap:Body>\
                         </soap:Envelope>",soapMethod,soapbody,soapMethod];
    
    self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
    // 设置请求超时时间
    self.manager.requestSerializer.timeoutInterval = 15;
    
    // 返回NSData
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // 设置请求头，也可以不设置
    [self.manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [self.manager.requestSerializer setValue:[NSString stringWithFormat:@"%zd", soapStr.length] forHTTPHeaderField:@"Content-Length"];
//    self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/xml",@"text/json", @"text/plain", @"text/html", nil];
    // 设置HTTPBody
    [self.manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
        return soapStr;
    }];
    ///石家庄数据 ：http://121.28.100.2:83/Phone/PhoneService.asmx
    ///保定数据 ： http://10.48.98.120:88/Phone/PhoneService.asmx
    //    测试数据：http://192.168.0.77:8080/phone/phoneservice.asmx
    self.task = [self.manager POST:@"http://192.168.0.77:8080/phone/phoneservice.asmx" parameters:soapStr progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 把返回的二进制数据转为字符串
        NSString *result = [[NSString alloc] initWithData:(NSData *)responseObject encoding:NSUTF8StringEncoding];
        // 利用正则表达式取出<return></return>之间的字符串
        NSString *regularStr = [NSString stringWithFormat:@"(?<=%@Result\\>).*(?=</%@Result)",soapMethod,soapMethod];
        NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:regularStr options:NSRegularExpressionCaseInsensitive error:nil];
        
        NSDictionary *dict = [NSDictionary dictionary];
//        NSString *str;
        for (NSTextCheckingResult *checkingResult in [regular matchesInString:result options:0 range:NSMakeRange(0, result.length)]) {
            
            // 得到字典
            dict = [NSJSONSerialization JSONObjectWithData:[[result substringWithRange:checkingResult.range] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
//            str = [result substringWithRange:checkingResult.range];
        }
        // 请求成功并且结果有值把结果传出去
        if (success && dict) {
            success(dict);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if(failure)
        {
            failure();
        }
        NSString *errorStr ;
        if(error.code == -1001)
        {
            errorStr = @"网络请求超时";
        }
        else if (error.code == -999){
            return ;
        }
        else if (error.code == -1009)
        {
            errorStr = @"网络未连接";
        }
        else
        {
            errorStr = @"服务器连接异常";
        }
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = errorStr;
        hud.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.5f];
        hud.offset = CGPointMake(0.f, 200);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        HLog(@"error-----------%@",error);
    }];
}


- (void)SOAPData:(NSDictionary *)pratams Http:(NSString *)httpStr soapMethod:(NSString *)soapMethod success:(void (^)(id))success failure:(void (^)(void))failure
{
    
    
    NSString *soapbody = [[NSString alloc] init];
    if (pratams.allKeys.count > 0) {
        for(NSString *str in pratams.allKeys)
        {
            soapbody = [soapbody stringByAppendingString:[NSString stringWithFormat:@"<%@>%@</%@>\\",str,[pratams objectForKey:str],str]];
        }
        
    }
    ////.net http://tempuri.org/
    //    NSString *soapStr = [NSString stringWithFormat:
    //                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\
    //                         <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.zhwy.com/\">\
    //                         <soapenv:Header>\
    //                         </soapenv:Header>\
    //                         <soapenv:Body>\
    //                         <ser:%@>\
    //                         %@\
    //                         </ser:%@>\
    //                         </soapenv:Body>\
    //                         </soapenv:Envelope>",soapMethod,soapbody,soapMethod];
    NSString *soapStr = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\
                         <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\
                         xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
                         <soap:Header>\
                         </soap:Header>\
                         <soap:Body>\
                         <%@ xmlns=\"http://tempuri.org/\">\
                         %@\
                         </%@>\
                         </soap:Body>\
                         </soap:Envelope>",soapMethod,soapbody,soapMethod];
    self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
    // 设置请求超时时间
    self.manager.requestSerializer.timeoutInterval = 30;
    
    // 返回NSData
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // 设置请求头，也可以不设置
    [self.manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [self.manager.requestSerializer setValue:[NSString stringWithFormat:@"%zd", soapStr.length] forHTTPHeaderField:@"Content-Length"];
    //   self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/xml",@"text/json", @"text/plain", @"text/html", nil];
    // 设置HTTPBody
    [self.manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
        return soapStr;
    }];
    
    self.task = [self.manager POST:httpStr parameters:soapStr progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 把返回的二进制数据转为字符串
        NSString *result = [[NSString alloc] initWithData:(NSData *)responseObject encoding:NSUTF8StringEncoding];
        // 利用正则表达式取出<return></return>之间的字符串
        NSString *regularStr = [NSString stringWithFormat:@"(?<=%@Result\\>).*(?=</%@Result)",soapMethod,soapMethod];
        NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:regularStr options:NSRegularExpressionCaseInsensitive error:nil];
        NSDictionary *dict = [NSDictionary dictionary];
        NSString *jsonStr;
        
        //        NSString *str;
        for (NSTextCheckingResult *checkingResult in [regular matchesInString:result options:0 range:NSMakeRange(0, result.length)]) {
            
            // 得到字典
            //   dict = [NSJSONSerialization JSONObjectWithData:[[result substringWithRange:checkingResult.range] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
            jsonStr  = [result substringWithRange:checkingResult.range];
            //注意接口传过来的数据带有&quot字样，需要替换成“ " "(引号)
            jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];//替换字符
            NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
            dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
            //            str = [result substringWithRange:checkingResult.range];
        }
        // 请求成功并且结果有值把结果传出去
        if (dict) {
            success(dict);
        }else{
            success(jsonStr);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if(failure)
        {
            failure();
        }
        NSString *errorStr ;
        if(error.code == -1001)
        {
            return ;
            
        }
        else if (error.code == -999){
            return ;
        }
        else if (error.code == -1009)
        {
            errorStr = @"网络未连接";
        }
        else
        {
            return;
        }
        for (UIView *view in [UIApplication sharedApplication].keyWindow.subviews) {
            if ([view isKindOfClass:[MBProgressHUD class]]) {
                [view removeFromSuperview];
            }
        }
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = errorStr;
        hud.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.5f];
        hud.offset = CGPointMake(0.f, 200);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        //        HLog(@"error-----------%@",error);
    }];
}


@end
